package com.note.simpleadmin.module.authc;

import com.note.simpleadmin.module.authc.service.BgUserService;
import com.note.simpleadmin.dto.UserInfo;
import com.note.simpleadmin.entity.BgUser;
import com.note.simpleadmin.utils.SpringContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShiroRealm extends AuthorizingRealm {
    private final static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.debug("登录验证后进行权限认证....");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("登录操作进行登录认证......");
        UsernamePasswordToken  token = (UsernamePasswordToken)authenticationToken;
        BgUserService bgUserService = SpringContextUtils.getContext().getBean(BgUserService.class);
        BgUser bgUser=bgUserService.findByUsername(token.getUsername());
        if (bgUser == null) {
            // 没找到帐号
            throw new UnknownAccountException("用户名或密码错误");
        }
        //简单验证
        ByteSource credentialsSalt = ByteSource.Util.bytes(bgUser.getSalt());
        UserInfo userInfo=new UserInfo();
        userInfo.setId(bgUser.getId());
        userInfo.setUsername(bgUser.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo,bgUser.getPwd(),credentialsSalt,getName());
        return info;
    }

}